from google.appengine.ext import bulkload
from google.appengine.api import datastore_types
from google.appengine.ext import search
from pyth.inventionmodels import *
import datetime


class MaterialLoader(bulkload.Loader):
  def __init__(self):
    # Our 'Person' entity contains a name string and an email
    #print 'here'
    bulkload.Loader.__init__(self, 'Material', 
                         [('name', str),
                            ('cost', str),
                            ('where', str),
                            ('tips', lambda x: datastore_types.Text(x.replace('\x0b', ' ').replace('\x1d', ' '))),
                            ('image', lambda x: 'materials/'+x),
                            ('type', str)
                          ])

  def HandleEntity(self, entity):
    # not sure what to do if multiple copies already exist
      exists = Material.gql("WHERE name = :1", entity['name'])
      if exists.count() == 0 or (exists.count() == 1 and exists[0].datetime < datetime.datetime.now()):
          m = Material()
          m.name = entity['name']
          m.cost = entity['cost']
          m.where = entity['where']
          m.tips = entity['tips']
          m.image = entity['image']
          m.type = entity['type']
          m.put()
          workshops = Workshop.gql('WHERE craft = :1', m.name)
          for w in workshops:
              MaterialRelationalEntry(material = m, workshop = w).put()
          workshops = Workshop.gql('WHERE hardware = :1', m.name)
          for w in workshops:
              MaterialRelationalEntry(material = m, workshop = w).put()
          workshops = Workshop.gql('WHERE software = :1', m.name)
          for w in workshops:
              MaterialRelationalEntry(material = m, workshop = w).put()
      return None

if __name__ == '__main__':
  bulkload.main(MaterialLoader())